package cn.edu.ysu.zry.network;

import cn.edu.ysu.zry.entity.Xieyi;
import cn.edu.ysu.zry.service.ServiceZhongxin;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: XieyiBlockChainOS
 * @description: 网络服务启动项 - 中心节点， 建议将本线程设置为守护线程
 * @author: Ruiyuan Zhang
 * @create: 2020-04-20 20:21
 */
public class NetWorkThreadZhongxin extends Thread {
    public static final int PORT=0623;
    public static final int THREAD_POOL_NUM=100;
    public static final String CHARACTER_ENCODING="UTF-8";

    /**
    *@Description: 启动项 - 用来启动监控服务, 该函数一旦启动就无法停止
    *@Param:
    *@return:
    *@Author: Ruiyuan Zhang
    *@date: 2020/4/20
    */
    public void run() {
        super.run();
        try {
            // 1 监听指定的端口
            int port = PORT;
            ServerSocket server = null;
            server = new ServerSocket(port);

            // 2 设置线程池 - 如果使用多线程，那就需要线程池，防止并发过高时创建过多线程耗尽资源
            ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_POOL_NUM);
            while (true) {
                Socket socket = server.accept();
                Runnable runnable=()->{
                    try {
                        // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
                        InputStream inputStream = socket.getInputStream();
                        byte[] bytes = new byte[1024];
                        int len;
                        StringBuilder sb = new StringBuilder();
                        while ((len = inputStream.read(bytes)) != -1) {
                            sb.append(new String(bytes, 0, len, CHARACTER_ENCODING));
                        }
                        handleMessage(sb.toString(),socket);
                        inputStream.close();
                        socket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                };
                threadPool.submit(runnable);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
    *@Description: 对收到的数据进行分发处理
    *@Param: result：要求收到的数据为json格式
    *@return:
    *@Author: Ruiyuan Zhang
    *@date: 2020/4/20
    */
    public void handleMessage(String result,Socket socket){
        try{
            // 1 将result对象转为json对象
            JSONObject jsonObject = new JSONObject(result);
            System.out.println(jsonObject);
            // 2 查看请求对象
            if(jsonObject.get("message")==null)return;
            if(jsonObject.get("message").equals(MessagePack.MESSAGE_ZHONGXIN.GET_ZHONG_LIST)){
                ServiceZhongxin.getZhongList(socket);
            }else if(jsonObject.get("message").equals(MessagePack.MESSAGE_ZHONGXIN.LINK_TO)){
                ServiceZhongxin.linkTo(jsonObject);
            }else if(jsonObject.get("message").equals(MessagePack.MESSAGE_ZHONGXIN.GET_PUBLIC_KEY)){

            }
        }catch (Exception e){
            e.printStackTrace();
            return;
        }
    }

//    @Test
//    public void f(){
//        MessagePack<Xieyi>messagePack=new MessagePack<Xieyi>();
//        messagePack.setMessage(MessagePack.MESSAGE_ZHONGXIN.GET_ZHONG_LIST);
//        Xieyi xieyi=new Xieyi();
//        xieyi.setHashXieyi("高素丽".getBytes());
//        messagePack.setData(xieyi);
//        handleMessage(JSONUtil.toJsonStr(messagePack));
//    }

}
